package cz.semjob.linguistic.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

public class Util {
	
	private static Logger logger = Logger.getLogger(Util.class);
	
	public static String inputStreamToString(InputStream stream) {
		StringWriter writer = new StringWriter();
		try {
			IOUtils.copy(stream, writer, "UTF-8");
		} catch (IOException e) {
			logger.warn("Could not write error message");
		}
		return writer.toString();
	}
	
	public static void executeCommand(String command) throws IOException {
		Process process = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", command});
		try {
			if (process.waitFor() != 0) {
				logger.error("Command '" + command + "' finished incorrectly!");
				logger.error(Util.inputStreamToString(process.getErrorStream()));
				throw new IOException("Command executing error");
			}
		} catch (InterruptedException e) {
			logger.warn(e);
		}
		logger.info(Util.inputStreamToString(process.getInputStream()));
	}

}
